<?php
header('Content-type: application/json; charset=UTF-8');

if (!mysql_connect("localhost","root","magnets")) {
	echo 'Problem!';
}

mysql_select_db("refrigerator");

if (isset($_REQUEST['id'])) {
	$id = $_REQUEST['id'];
	
	$result = mysql_query("SELECT * FROM problems WHERE id = '$id'");
	
	$rows = array();
	
	while($r = mysql_fetch_assoc($result)) {
		$r["numbers"] = $r["statements"];
		$r["innerFunctions"] = get_statement($r["innerFunctions"]);
		$r["forLeft"]    = get_statement($r["forLeft"]);
		$r["forMid"]     = get_statement($r["forMid"]);
		$r["forRight"]   = get_statement($r["forRight"]);
		$r["booleans"]   = get_statement($r["booleans"]);
		$r["statements"] = get_statement($r["statements"]);
		
		$rows[] = $r;
	}
	
	echo json_encode($rows);
}

function get_statement($input) 
{
	$statement = array();
	$i = 0;
	
    $arr = explode(",", $input);
	
	foreach($arr as $val) {
		$query = "SELECT data FROM problemdata WHERE id = '$val'";
		$result = mysql_query($query);
		$rows = mysql_fetch_array($result);
		$statement[$i] = $rows["data"];
		
		$i++;
	}
	
	return $statement;
}

?>